//API:http://api.uihoo.com/demo/qrcode.shtml#body_top
var db = require("../../core/db/index");
var config = require("../../core/_include/config");
var qiniu = require("./qiniu");
var http = require("http");
var fs = require("fs");
var qrcode = {
	getConfig: function(info) {
		return {
			"string": info.str,
			"bgc": "FFFFFF",
			"fgc": "000000",
			"logo": info.logo || "http://www.dotnar.com/images/logo.png",
			"logosize": "0.4",
			"el": "3",
			"format": "json",
		};
	},
	get: function(info, successcb, errorcb) {
		info = qrcode.getConfig(info);
		console.log(info);

		var data = db.find_one(config.dbname.qrcode, {
			info: info
		});
		if (data) {
			successcb(data);
		} else {
			qrcode.upload(info, function(filePath,info_com) {
				qiniu.upload(filePath, function(error, ret) {
					//上传完成后，删除缓存文件
					fs.unlink(filePath);
					if (error) {
						errorcb && errorcb(new Error("上传权限有误"))
						return;
					}
					var data = {
						_id: config.dbIdPrefix.qrcode + Math.random().toString(16).substr(2) + (+new Date).toString(16),
						info: info_com,
						result: ret
					}
					db.insert(config.dbname.qrcode, data);
					successcb && successcb(data);
				})
			})
		}
	},
	upload: function(info, successcb, errorcb) {
		info.string||(info = qrcode.getConfig(info))
		var baseUrl = "http://api.uihoo.com/qrcode/qrcode.http.php";
		var urlQuerys = []
		for (var key in info) {
			urlQuerys.push(encodeURIComponent(key) + "=" + encodeURIComponent(info[key]));
		}
		var url = baseUrl + "?" + urlQuerys.join("&");
		console.log("url:", url);

		http.get(url, function(res) {
			var result = ""
			res.on("data", function(data) {
				result += data
			}).on("end", function() {
				try {
					var jsonData = Function("return " + result)();
					var base64_data = jsonData.base64.split("\r\n").join("");

					var matches = base64_data.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);

					if (matches.length !== 3) {
						self.body = ResponObj("error", "Invalid input string");
					}

					var file_buffer = new Buffer(matches[2], 'base64');
					var file_type = matches[1];
					if (file_type.indexOf("image\/") !== 0) {
						// self.body = ResponObj("error", "上传的文件不是图片类型");
						errorcb && errorcb(new Error("上传的文件不是图片类型"))
					}

					var filePath = __dirname + "/../_temp/" + Math.random().toString(36).substring(2) + "." + file_type.substring(6);
					fs.writeFile(filePath, file_buffer, function() {
						successcb && successcb(filePath, info)
					});
				} catch (e) {
					errorcb && errorcb(e)
				}
			});
		});
	}
};
module.exports = qrcode;